<template>
  <div class="address-selector">
    <!-- 当前选中的地址 -->
    <div v-if="selectedAddress" class="selected-address" @click="showAddressList = true">
      <div class="address-info">
        <div class="receiver-info">
          <span class="name">{{ selectedAddress.receiverName }}</span>
          <span class="phone">{{ selectedAddress.receiverPhone }}</span>
          <el-tag v-if="selectedAddress.isDefault === 1" type="primary" size="small">默认</el-tag>
        </div>
        <div class="address-detail">
          {{ selectedAddress.fullAddress }}
        </div>
      </div>
      <el-icon class="arrow-icon">
        <ArrowRight />
      </el-icon>
    </div>

    <!-- 没有地址时的提示 -->
    <div v-else class="no-address" @click="showAddressList = true">
      <el-icon class="add-icon">
        <Plus />
      </el-icon>
      <span>请选择收货地址</span>
      <el-icon class="arrow-icon">
        <ArrowRight />
      </el-icon>
    </div>

    <!-- 地址列表弹窗 -->
    <el-dialog
      v-model="showAddressList"
      title="选择收货地址"
      width="600px"
      :before-close="handleClose"
    >
      <div class="address-list">
        <!-- 地址列表 -->
        <div v-if="addresses.length > 0" class="address-items">
          <div
            v-for="address in addresses"
            :key="address.id"
            class="address-item"
            :class="{ active: selectedAddress?.id === address.id }"
            @click="selectAddress(address)"
          >
            <div class="address-content">
              <div class="receiver-info">
                <span class="name">{{ address.receiverName }}</span>
                <span class="phone">{{ address.receiverPhone }}</span>
                <el-tag v-if="address.isDefault === 1" type="primary" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ address.fullAddress }}
              </div>
            </div>
            <div class="address-actions">
              <el-button type="text" @click.stop="editAddress(address)">编辑</el-button>
              <el-button 
                v-if="address.isDefault !== 1" 
                type="text" 
                @click.stop="setDefault(address)"
              >
                设为默认
              </el-button>
              <el-button 
                type="text" 
                class="delete-btn" 
                @click.stop="deleteAddress(address)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无收货地址" />
        </div>

        <!-- 添加新地址按钮 -->
        <div class="add-address-btn">
          <el-button type="primary" @click="showAddressForm = true">
            <el-icon><Plus /></el-icon>
            添加新地址
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 地址表单弹窗 -->
    <el-dialog
      v-model="showAddressForm"
      :title="editingAddress ? '编辑地址' : '添加地址'"
      width="500px"
      :before-close="handleFormClose"
    >
      <!-- 地址表单 -->
      <AddressForm
        ref="addressFormRef"
        v-model="addressForm"
        :is-edit="!!editingAddress"
        @update:modelValue="updateAddressForm"
      />
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleFormClose">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="saving">
            {{ editingAddress ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight, Plus, Edit, Delete, Star } from '@element-plus/icons-vue'
import { addressApi, type Address, type CreateAddressRequest } from '@/api/address'
import { useUserStore } from '@/stores/user'
import AddressForm from './AddressForm.vue'

// Props
interface Props {
  modelValue?: Address | null
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [address: Address | null]
  'change': [address: Address | null]
}>()

// Store
const userStore = useUserStore()

// 响应式数据
const addresses = ref<Address[]>([])
const loading = ref(false)
const saving = ref(false)
const showAddressList = ref(false)
const showAddressForm = ref(false)
const editingAddress = ref<Address | null>(null)

// 表单相关
const addressFormRef = ref()
const addressForm = reactive<CreateAddressRequest>({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  postalCode: '',
  isDefault: 0
})

// 监听 addressForm 变化
watch(addressForm, (newValue) => {
  console.log('AddressSelector addressForm 数据变化:', newValue)
}, { deep: true })

// 添加一个方法来手动更新 addressForm
const updateAddressForm = (newData: CreateAddressRequest) => {
  console.log('手动更新 addressForm:', newData)
  Object.assign(addressForm, newData)
}

// 计算属性
const selectedAddress = computed({
  get: () => props.modelValue,
  set: (value: Address | null) => {
    emit('update:modelValue', value)
    emit('change', value)
  }
})

// 方法
const loadAddresses = async () => {
  if (!userStore.userInfo?.userId) return
  
  try {
    loading.value = true
    const response = await addressApi.getUserAddresses(userStore.userInfo.userId)
    addresses.value = response.data
    
    // 如果没有选中地址，自动选择默认地址
    if (!selectedAddress.value && addresses.value.length > 0) {
      const defaultAddr = addresses.value.find(addr => addr.isDefault === 1)
      if (defaultAddr) {
        selectedAddress.value = defaultAddr
      }
    }
  } catch (error) {
    console.error('加载地址列表失败:', error)
    ElMessage.error('加载地址列表失败')
  } finally {
    loading.value = false
  }
}

const selectAddress = (address: Address) => {
  selectedAddress.value = address
  showAddressList.value = false
}

const editAddress = (address: Address) => {
  console.log('编辑地址，原始数据:', address)
  editingAddress.value = address
  
  // 逐个赋值以确保响应式更新
  addressForm.receiverName = address.receiverName
  addressForm.receiverPhone = address.receiverPhone
  addressForm.province = address.province
  addressForm.city = address.city
  addressForm.district = address.district
  addressForm.address = address.address
  addressForm.postalCode = address.postalCode || ''
  addressForm.isDefault = address.isDefault
  
  console.log('编辑地址，更新后的 addressForm:', addressForm)
  showAddressForm.value = true
}

const setDefault = async (address: Address) => {
  if (!userStore.userInfo?.userId) return
  
  try {
    await addressApi.setDefaultAddress(userStore.userInfo.userId, address.id)
    ElMessage.success('设置默认地址成功')
    await loadAddresses()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

const deleteAddress = async (address: Address) => {
  if (!userStore.userInfo?.userId) return
  
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await addressApi.deleteAddress(userStore.userInfo.userId, address.id)
    ElMessage.success('删除地址成功')
    
    // 如果删除的是当前选中的地址，清空选中状态
    if (selectedAddress.value?.id === address.id) {
      selectedAddress.value = null
    }
    
    await loadAddresses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }
}

const saveAddress = async () => {
  if (!userStore.userInfo?.userId || !addressFormRef.value) return
  
  try {
    await addressFormRef.value.validate()
    saving.value = true
    
    // 确保数据不为空
    console.log('保存地址数据:', addressForm)
    
    if (editingAddress.value) {
      // 更新地址
      await addressApi.updateAddress(userStore.userInfo.userId, editingAddress.value.id, addressForm)
      ElMessage.success('更新地址成功')
    } else {
      // 创建地址
      await addressApi.createAddress(userStore.userInfo.userId, addressForm)
      ElMessage.success('添加地址成功')
    }
    
    await loadAddresses()
    handleFormClose()
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败')
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  showAddressList.value = false
}

const handleFormClose = () => {
  showAddressForm.value = false
  editingAddress.value = null
  addressFormRef.value?.resetFields()
  Object.assign(addressForm, {
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    postalCode: '',
    isDefault: 0
  })
}

// 生命周期
onMounted(() => {
  loadAddresses()
})
</script>

<style scoped>
.address-selector {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
}

.selected-address,
.no-address {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.selected-address:hover,
.no-address:hover {
  background-color: #f5f7fa;
}

.address-info {
  flex: 1;
}

.receiver-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.receiver-info .name {
  font-weight: 600;
  color: #303133;
}

.receiver-info .phone {
  color: #606266;
}

.address-detail {
  color: #909399;
  font-size: 14px;
  line-height: 1.4;
}

.no-address {
  color: #909399;
  justify-content: center;
  gap: 8px;
}

.add-icon {
  font-size: 18px;
}

.arrow-icon {
  color: #c0c4cc;
  font-size: 16px;
}

.address-list {
  max-height: 400px;
  overflow-y: auto;
}

.address-items {
  margin-bottom: 16px;
}

.address-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.address-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.address-content {
  flex: 1;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f56c6c;
}

.add-address-btn {
  text-align: center;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>